import { initSearchConfig, TableSearchPanel, XxpageContainer, XxRangePicker, XxTable } from "@/ui";
import React, { useContext, useEffect, useRef, useState } from "react";
import UserForm from "./userForm";
import { userApi } from "@/api";
import { message, Modal, Select } from "antd";
import { Context, globalModal, mobxState } from "@/data";
import { getColumns, getActoinPanel, getSearchFields } from "./config";
import { deleteConfirm, successAlert } from "@/common/methods";


/**
 * 列表视图组件
 * @description 展示用户列表、支持搜索、分页、编辑、删除、角色分配等功能
 * @component
 * @returns {JSX.Element} 返回用户列表页面组件
 * 
 * 功能包括:
 * - 用户列表展示与分页
 * - 搜索过滤
 * - 新增/编辑用户
 * - 删除用户
 * - 角色分配
 * - 表格行选择
 * - 双击行事件
 */
const UserListView = () => {
    const { modal } = useContext(Context);
    console.log("context", modal);


    /** 
     * 搜索表单的引用对象，用于获取/操作表单实例
     * @type {React.MutableRefObject<FormInstance>}
    */
    const searchFormRef = useRef(null);
    /** 
     * 用于引用编辑表单的 ref 对象
     * @type {React.MutableRefObject<null>}
     */
    const editFormRef = useRef(null);
    const [params, setParams] = useState({ ...initSearchConfig(getSearchFields({ searchFormRef })) })
    const [state, setState] = useState({
        data: [],
        totalCount: 0
    })
    const [loading, setLoading] = useState(false);

    //搜索事件
    const onClickSearch = (value) => {
        setParams({
            ...params,
            ...value,
            current: 1,
        });
    };


    /**@description 查找菜单列表 */
    const getList = async () => {
        setLoading(true);
        const { data, msg, code } = await userApi.getUserList({ pageSize: 10, current: 1 });
        setState({
            data: [...data.list],
            totalCount: data.totalCount || 0
        })
        setLoading(false);

    }

    /**
     * 处理分页变化的回调函数
     * @param {number} current - 当前页码
     * @param {number} pageSize - 每页显示条数
     * @description 更新分页参数状态，触发数据重新加载
     */
    const onChange = (current, pageSize) => {
        setParams({
            ...params,
            current,
            pageSize
        })
    }
    useEffect(() => {
        getList()
    }, [params])

    /**
     * 打开用户表单弹窗
     * @param {Object} params - 打开弹窗的参数
     * @param {string} [params.type='add'] - 弹窗类型，默认为'add'(新增)
     * @param {Object} [params.record=Object] - 编辑时的用户记录数据
     */
    const open = ({ type = "add", record = Object }) => {
        editFormRef.current.open({ type, record });
    }

    /**@description 删除按钮操作 */
    const handleDelete = async (record) => {
        try {
            await deleteConfirm();
            const { code, msg } = await userApi.deleteMenu(record.id)
        } catch {

        } finally {
            getList()
        }
    }

    /**
     * @description 更换角色
     */
    const onChangeRole = (record) => {
        let params = {
            userName: record.userName,
            userId: record.userId,
            user_id: record._id,
            roleId: null,
            roleName: null,
        }
        modal.confirm({
            centered: true,
            title: "分配角色",
            content: <div style={{ width: '100%' }}>
                <Select
                    defaultValue={record.roleId}
                    style={{ width: '100%' }}
                    options={mobxState.allRoles}
                    fieldNames={{
                        label: "roleName",
                        value: "roleId"
                    }}
                    onChange={(value, options) => {
                        console.log("当前选择的:", value, options);
                        const { roleName, roleId } = options;
                        params = {
                            ...params,
                            roleName,
                            roleId
                        }
                    }}
                />
            </div>,
            onOk: async (onClose) => {
                const data = await userApi.updateUser(params);
                message.success("保存成功");
                onClose();
                getList();
            }
        })
    }


    const [selectedKeys, setSelectedKeys] = useState([])
    const onSelectChange = (newSelectedRowKeys, selectedRows) => {
        setSelectedKeys(newSelectedRowKeys);
    }
    const actionPanel = getActoinPanel({
        editForm: open
    })
    const tableProps = {
        tablePanelConfig: actionPanel,
        loading,
        columns: getColumns({ open, handleDelete, onChangeRole }),
        dataSource: state.data,
        pagination: {
            total: state.totalCount,
            pageSize: params.pageSize,
            onChange: onChange,
            current: params.current

        },
        rowSelection: {
            type: "checkbox",
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
        },
        rowKey: '_id',
        selectedRowKeys: selectedKeys,
        onRow: (record, index) => {
            return {
                onDoubleClick: () => {
                    console.log("双击", record);
                }
            }
        },
    }


    return (
        <XxpageContainer>
            <UserForm onRef={editFormRef} getList={getList} />
            <TableSearchPanel
                onRef={searchFormRef}
                fields={getSearchFields({ searchFormRef })}
                onSearch={onClickSearch}

            />
            <XxTable  {...tableProps} />

        </XxpageContainer>
    )
}

export default UserListView;